jQuery(function () {

	// REQUEST HANDLERS //
	
	function onCategoriesReceived(data) {
		if (data.error == null) {
			addCategories(data.data);
		}
	};

	function onPostReceived(data) {
		console.log(JSON.stringify(data));
		if (data.error == null && data != "") {
			addTitle(data.data.title);
			addDate(data.data.date);
			addPost(data.data.content);
		}
	};

	// BLOG HANDLERS //

	function addCategories(categories) {
		for (var i = 0; i < categories.length; i++) {
			jQuery("<li></li>").appendTo("#categories ul").append(
				jQuery("<a></a>", {
					text: categories[i].value,
					href: "#"
			}));
		}
	};

	function addPost(content) {
		var paragrafs = content.split("\n\n\n");
		removePost();

		for (var i = 0; i < paragrafs.length; i++) {
			createPostParagraf(paragrafs[i]);
		}
	};

	function createPostParagraf(data) {
		var value = snippetRegex.exec(data);

		if (value != null) {
			value = value.toString();
			var length = value.length;

			importLibrary(value);
			$snippetTemplate.clone().addClass(value).text(data.
				slice(length + 4, -length - 5)).appendTo("#article");
		} else {
			jQuery("<p></p>", {
				text: data
			}).appendTo("#article");
		}
	};

	function addTitle(title) {
		jQuery("#blogTitle").text(title);
	};

	function addDate(value) {
		var date = new Date(value);
		jQuery("#datetime").text(date.toDateString());
	}

	function removePost() {
		jQuery("#article").empty();
	};

	// UTIL METHODS //
	
	function getURLParameter(name) {
		var result = new RegExp("[\\?&]" + name + "=([^&#]*)").exec(window.location.href);
		return (result != null ? result[1] : null);
	};

	function importLibrary(name) {
		if (libMap[name] == null) {
			$.getScript("../libs/" + name + ".js", function(event) {
				libMap[name] = true;
				SyntaxHighlighter.highlight();
			});
		}
	};

	// MAIN //
	
	var categotyURL = "http://springleafweb.appspot.com/get-all-categories";
	var postURL = "http://springleafweb.appspot.com/get-blog-post";
	var post = getURLParameter("post");
	var libMap = new Object();

	var snippetRegex = new RegExp("[^\\[\\[].*(?=\\]\\])", "im");

	var $snippetTemplate = $("<pre></pre>").addClass("brush: ");

	jQuery.get(categotyURL, onCategoriesReceived);
	jQuery.get((post != null ? postURL + "?post=" + post : postURL), onPostReceived);
});